const app = getApp();
const util = require('../../utils/util.js');

Page({
  data: {
    tabs: ['A → B', 'B → A'],
    activeTab: 0,
    date: '',
    dateText: '今日',
    isFixed: true,
    schedules: [],
    loading: false,
    page: 0,
    size: 10,
    hasMore: true
  },
  
  onLoad() {
    // 设置当前日期
    const today = new Date();
    const date = today.getFullYear() + '-' + 
                this.padZero(today.getMonth() + 1) + '-' + 
                this.padZero(today.getDate());
    
    this.setData({
      date: date
    });
    
    this.loadSchedules(true);
  },
  
  onShow() {
    // 检查用户是否登录
    if (!app.globalData.token) {
      wx.redirectTo({
        url: '/pages/login/login'
      });
      return;
    }
    
    // 更新自定义tabBar选中状态
    if (typeof this.getTabBar === 'function' && this.getTabBar()) {
      this.getTabBar().setData({
        selected: 0
      });
    }
  },
  
  onPullDownRefresh() {
    this.loadSchedules(true);
  },
  
  onReachBottom() {
    if (this.data.hasMore && !this.data.loading) {
      this.loadSchedules();
    }
  },
  
  switchTab(e) {
    const index = parseInt(e.currentTarget.dataset.index);
    if (this.data.activeTab !== index) {
      this.setData({
        activeTab: index,
        page: 0,
        hasMore: true,
        schedules: []
      });
      this.loadSchedules(true);
    }
  },
  
  selectDate() {
    const that = this;
    wx.showActionSheet({
      itemList: ['今日', '明日', '后日'],
      success: function(res) {
        if (!res.cancel) {
          const today = new Date();
          let targetDate = new Date(today);
          targetDate.setDate(today.getDate() + res.tapIndex);
          
          const date = targetDate.getFullYear() + '-' + 
                       that.padZero(targetDate.getMonth() + 1) + '-' + 
                       that.padZero(targetDate.getDate());
          
          that.setData({
            date: date,
            dateText: ['今日', '明日', '后日'][res.tapIndex],
            page: 0,
            hasMore: true,
            schedules: []
          });
          
          that.loadSchedules(true);
        }
      }
    });
  },
  
  switchScheduleType() {
    this.setData({
      isFixed: !this.data.isFixed,
      page: 0,
      hasMore: true,
      schedules: []
    });
    this.loadSchedules(true);
  },
  
  loadSchedules(refresh) {
    if (this.data.loading) return;
    
    this.setData({
      loading: true
    });
    
    if (refresh) {
      this.setData({
        page: 0,
        schedules: []
      });
      wx.showNavigationBarLoading();
    }
    
    const routeDirection = this.data.activeTab === 0 ? 'A_to_B' : 'B_to_A';
    
    app.request({
      url: `/schedules?date=${this.data.date}&routeDirection=${routeDirection}&isFixed=${this.data.isFixed}&page=${this.data.page}&size=${this.data.size}`,
      method: 'GET'
    }).then(res => {
      // 将后端返回的数据转换为前端需要的格式
      const schedules = res.content.map(item => {
        return {
          id: item.id,
          departureTime: item.departureTime,
          arrivalTime: item.arrivalTime,
          availableSeats: item.availableSeats,
          capacity: item.capacity,
          bookedSeats: item.bookedSeats,
          price: item.price,
          status: item.status,
          driver: item.driver ? {
            name: item.driver.name,
            phone: item.driver.phoneNumber
          } : null
        };
      });
      
      this.setData({
        schedules: refresh ? schedules : this.data.schedules.concat(schedules),
        page: this.data.page + 1,
        hasMore: res.totalPages > (this.data.page + 1),
        loading: false
      });
      
      if (refresh) {
        wx.hideNavigationBarLoading();
        wx.stopPullDownRefresh();
      }
    }).catch(err => {
      this.setData({
        loading: false
      });
      
      if (refresh) {
        wx.hideNavigationBarLoading();
        wx.stopPullDownRefresh();
      }
      
      wx.showToast({
        title: err.message || '加载失败',
        icon: 'none'
      });
    });
  },
  
  viewScheduleDetail(e) {
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/schedule-detail/schedule-detail?id=${id}`,
    });
  },
  
  padZero(num) {
    return num < 10 ? '0' + num : num;
  }
}) 